<template>
    <el-container>
        <el-main>
            <el-form ref="productForm" :model="form" label-width="90px">

                    <el-form-item label="商品名称" style="width: 700px">
                        <span>{{form.name}}</span>
                    </el-form-item>


                  <el-form-item label="使用说明" style="width: 600px">
                    <el-input v-model="form.subTitle" placeholder="在商品以副标题形式展示" />
                  </el-form-item>


                  <el-row style="display: flex; justify-content: flex-end; position: relative; margin-left: 33px">
                          <el-col :span="23">
                                <el-table :data="productList" border stripe>
                                    <el-table-column label="货号/条码" width="120">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.sn" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="商品图片" width="80" align="center">
                                        <template slot-scope="{row}">
                                            <single-upload v-model="row.thumbnail" list-type="picture-card" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="单位" width="70">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.unit" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="市场价" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.marketPrice" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="销售价" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="成本价" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.cost" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>0" :label="vips[0].name" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip1price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>1" :label="vips[1].name" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip2price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>2" :label="vips[2].name" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip3price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>3" :label="vips[3].name" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip4price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>4" :label="vips[4].name" width="85">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip5price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                        <el-row style="margin-top: 20px">



                            <el-form-item label="分销策略" style="width: 300px">
                              <el-select v-model="form.distributionId" style="width: 100%" placeholder="请选择">
                                <el-option v-for="(item,index) in disOptions" :key="index" :label="item.name" :value="item.id" />
                              </el-select>
                            </el-form-item>

                            <el-form-item label="最小订购量" style="width: 300px">
                              <el-input v-model="form.minLimit" type="number" @mousewheel.native.prevent />
                            </el-form-item>

                          <el-form-item label="商品标签" style="width: 400px">
                            <el-select v-model="tagIds" style="width: 100%" multiple placeholder="请选择">
                              <el-option v-for="(item,index) in tagOptions" :key="index" :label="item.name" :value="item.id" />
                            </el-select>
                          </el-form-item>

                        </el-row>

                <el-form-item>
                    <el-button style="margin-top: 30px" type="primary" :loading="clicked" @click="editProduct('productForm')">
                        &nbsp&nbsp完 成&nbsp&nbsp
                    </el-button>
                </el-form-item>


            </el-form>

        </el-main>
    </el-container>
</template>
<style lang="scss" scoped>
.photo-content {
    width: 100%;
    display: flex;
    align-items: flex-end;
    border-top: 1px #eee solid;
    margin-bottom: 20px;
    margin-top: 10px;
}
/deep/.el-input__inner {
    padding: 0 5px;
}
/deep/ .el-upload--picture-card {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
    .menu-wrapper {
        margin: 15px;
    }
}
</style>
<script>
import { mapGetters } from "vuex";
import { list as vipList } from "@/api/vip";
import permission from "@/directive/permission/index.js"; // 权限判断指令
import MultiUpload from "@/components/Upload/multiUpload";
import multiUploadDraggable from "@/components/Upload/multiUploadDraggable";

import VideoUpload from "@/components/Upload/videoUpload";
import Tinymce from "@/components/Tinymce";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import { EventBus } from "@/api/eventBus";
import utils from "../../utils/utils.js";
import { list as freightList } from "@/api/freight";
import { find, update } from "@/api/product";
import { find as findInfo, update as updateInfo } from "@/api/productArticle";
import { list as tagList } from "@/api/tag";
import SingleUpload from "@/components/Upload/singleUpload";
import { list as distributionList } from "@/api/distribution.js";
import { getMenuTree as MenuTree } from "@/api/sysMch";
export default {
    name: "product-edit",
    directives: { elDragDialog, permission },
    filters: {},
    components: {
        SingleUpload,
        MultiUpload,
        VideoUpload,
        Tinymce,
        multiUploadDraggable,
    },
    data() {
        return {
            id: "",
            vips: [],
            length: 0,
            times: null,
            isCount: true,
            clicked: false, // 按钮防双击
            typeDisabled: false,
            productTypeOptions: [
                {
                    id: 10,
                    name: "实物商品",
                    childrens: [{ id: 20, name: "普通商品" }],
                },
                {
                    id: 11,
                    name: "虚拟商品",
                    childrens: [
                        { id: 20, name: "商品" },
                        { id: 21, name: "套餐" },
                    ],
                },
                {
                    id: 12,
                    name: "购物券商品",
                },
            ],
            article: {
                id: "",
                goods: "",
                productMeta: {
                    label: "",

                    images: [],
                    video: "",
                },
                content: "",
            },
            form: {
                maxLimit: "",
                publishType: 0,
                id: "",
                name: "",
                productCategoryId: "",
                shortName: "",
                orders: "",
                type: "1",
                freightId: "",
                shippingMethod: [],
                isMarketable: false,
                subTitle: "",
                minLimit: "",
                // labal: '',
                quality: "",
                distributionId: "",
                brandId: "",
                stock: "",
                supplierId: "",
                allocatedStock: "",
                weight: "",
                goodsId: "",
            },
            tagIds: [],
            disOptions: [],
            tagOptions: [],
            productList: [
                {
                    isClick: false,
                    isFirst: true,
                    maxLimit: "",
                    length: 0,
                    publishType: 0,
                    isList: true,
                    name: "",
                    productCategoryId: "",
                    shortName: "",
                    orders: 0,
                    type: "1",
                    freightId: "",
                    isMarketable: false,
                    subTitle: "",
                    minLimit: "",
                    // labal: '',
                    quality: "",
                    isChose: false,
                    isCount: false,
                    distributionId: "",
                    brandId: "",
                    stock: "",
                    supplierId: "",
                    allocatedStock: "",
                    weight: "",
                    subType: 2,
                    shippingMethod: "",
                    // ------
                    sn: "",
                    thumbnail: "",
                    spec1: "",
                    spec2: "",
                    unit: "",
                    unitRate: "",
                    marketPrice: "",
                    price: "",
                    cost: "",
                    point: "",
                    unitType: "",
                    vip1price: "",
                    vip2price: "",
                    vip3price: "",
                    vip4price: "",
                    vip5price: "",
                    article: {
                        productMeta: {
                            images: [],
                            video: "",
                            label: "",
                        },
                        content: "",
                    },
                },
            ],
            type: null,
        };
    },
    watch: {
        // 路由地址不变的情况下,如果id变化则重新获取数据
        $route(newVal, oldVal) {
            console.log(newVal);
            if (
                newVal.name == "waterTicket-edit" &&
                newVal.query.id != this.id
            ) {
                this.getFindData();
            }
        },
    },
    computed: {
        ...mapGetters(["scoreType"]),
    },
    created() {
        this.getFindData();
        EventBus.$on("freight-add", (res) => {
            // 监听新增完毕
            // 更新列表数组
            this.freightNames.splice(0, 0, res);
        });
        this.loadMenuTree();
        this.loadVip();
        this.loadTag();
        this.loadDistribution();
    },
    activated() {},
    methods: {
        loadMenuTree() {
            if (this.scopeType == 3) {
                this.productTypeOptions[0].childrens.push({
                    id: 24,
                    name: "管理空桶",
                });
                this.productTypeOptions[1].childrens.push({
                    id: 23,
                    name: "押金",
                });
                this.productTypeOptions[1].childrens.push({
                    id: 22,
                    name: "水票",
                });
            }
        },
        getFindData() {
            this.times = new Date().getSeconds();
            this.id = this.$route.query.id;
            var _this = this;
            find(this.id)
                .then((response) => {
                    console.log(response);
                    _this.article = response.data.article;
                    _this.length = response.data.products.length - 1;
                    for (var k = 0; k < response.data.products.length; k++) {
                        this.length = k;
                        response.data.products[k]["length"] = this.length;
                    }
                    for (var i = 1; i < response.data.products.length; i++) {
                        if (response.data.products[i].unitType == 2) {
                            response.data.products[i]["isCount"] = false;
                        } else {
                            response.data.products[i]["isCount"] = true;
                        }
                        if (response.data.products[0].unitType == 0) {
                            response.data.products[i]["isClick"] = true;
                            response.data.products[i]["isChose"] = true;
                        } else {
                            response.data.products[i]["isClick"] = false;
                            response.data.products[i]["isChose"] = false;
                        }
                    }

                    response.data.products[0]["isFirst"] = true;

                    _this.productList = response.data.products;
                    _this.tagIds = [];
                    if (!utils.isNull(this.productList[0].tags)) {
                        _this.productList[0].tags.forEach(function (item) {
                            _this.tagIds.push(item.id);
                        });
                    }

                    this.productList.forEach((item) => {
                        if (item.isList) {
                            this.form.maxLimit = item.maxLimit;
                            this.form.id = item.id;
                            this.form.name = item.name;
                            this.categoryName = item.productCategoryName;
                            this.form.productCategoryId =
                                item.productCategoryId;
                            this.form.shortName = item.shortName;
                            this.form.orders = item.orders;
                            this.form.type = item.type;
                            this.form.subType = item.subType;
                            this.form.isMarketable = item.isMarketable;
                            this.form.subTitle = item.subTitle;
                            this.form.minLimit = item.minLimit;
                            // this.form.labal = item.labal;
                            this.form.quality = item.quality;
                            this.form.distributionId = item.distributionId;
                            this.form.brandId = item.brandId;
                            this.form.stock = item.stock;
                            this.form.supplierId = JSON.stringify(
                                item.supplierId
                            );
                            this.form.allocatedStock = item.allocatedStock;
                            this.form.weight = item.weight;
                            this.form.goodsId = item.goodsId;
                            this.form.freightId = item.freightId;
                            if (item.shippingMethod) {
                                if (!utils.isNull(item.shippingMethod)) {
                                    _this.form.shippingMethod = item.shippingMethod.split(
                                        ","
                                    );
                                } else {
                                    _this.form.shippingMethod = ["0"];
                                }
                            } else {
                                _this.form.shippingMethod = ["0"];
                            }
                        }
                    });
                    this.supplierName = response.data.supplierName;
                    this.brandName = response.data.brandName;
                    console.log(_this.form);
                })
                .catch((error) => {
                    console.log(error.content);
                });
        },
        loadDistribution() {
            distributionList()
                .then((res) => {
                    this.disOptions = res.data.data;
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        loadVip() {
            vipList().then((res) => {
                res.data.data.forEach((item) => {
                    if (item.vip > 0) {
                        this.vips.push(item);
                    }
                });
                this.vips = this.vips.sort(this.compare("vip", true));
            });
        },
        compare(property, desc) {
            return function (a, b) {
                var value1 = a[property];
                var value2 = b[property];
                if (desc == true) {
                    // 升序排列
                    return value1 - value2;
                } else {
                    // 降序排列
                    return value2 - value1;
                }
            };
        },

        loadTag() {
            const _this = this;
            const params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 1000);
            params.append("type", 3);
            tagList(params)
                .then((response) => {
                    console.log(response);
                    _this.tagOptions = response.data.data;
                })
                .catch((error) => {});
        },
        dialogShow() {
            console.log("点击了");
            this.$refs.categoryDialog.show();
        },

        addProduct() {
            this.length += 1;
            this.productList.push({
                isList: false,
                name: "",
                isClick: true,
                productCategoryId: "",
                shortName: "",
                orders: 0,
                isFirst: false,
                length: this.length,
                type: "1",
                publishType: 0,
                isCount: this.isCount,
                isMarketable: false,
                subTitle: "",
                freightId: "",
                minLimit: "",
                maxLimit: "",
                // labal: '',
                quality: "",
                shippingMethod: "",
                distributionId: "",
                brandId: "",
                stock: "",
                supplierId: "",
                allocatedStock: "",
                weight: "",
                subType: "2",
                // -----
                sn: this.productList[0].sn,
                thumbnail: this.productList[0].thumbnail,
                spec1: this.productList[0].spec1,
                spec2: this.productList[0].spec2,
                unit: this.productList[0].unit,
                unitRate: this.productList[0].unitRate,
                marketPrice: this.productList[0].marketPrice,
                price: this.productList[0].price,
                cost: this.productList[0].cost,
                unitType: "",
                vip1price: this.productList[0].vip1price,
                vip2price: this.productList[0].vip2price,
                vip3price: this.productList[0].vip3price,
                vip4price: this.productList[0].vip4price,
                vip5price: this.productList[0].vip5price,
                isChose: false,
                point: this.productList[0].point,
                article: {
                    productMeta: {
                        label: "",
                        images: [],
                        video: "",
                    },
                    content: "",
                },
            });
            if (
                this.productList.length > 1 &&
                this.productList[0].unitType === 1
            ) {
                for (var l = 1; l < this.productList.length; l++) {
                    if (this.productList[l].unitType === 2) {
                        this.productList[this.length].isCount = true;
                    }
                }
            }
            if (this.productList.length > 1) {
                if (this.productList[0].unitType === 0) {
                    for (var i = 1; i < this.productList.length; i++) {
                        this.productList[i].unitType = 0;
                        this.productList[i].isChose = true;
                    }
                }
            }
            this.setAddClickHeight();
        },
        delProduct(row) {
            var index = this.productList.indexOf(row);
            if (index !== -1) {
                this.productList.splice(index, 1);
            }
            this.setAddClickHeight();
        },
        editProduct(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                if (valid) {
                    // 校验表单
                    _this.clicked = true;
                    const params = new URLSearchParams();
                    _this.tagIds.forEach(function (item) {
                        params.append("tagIds", item);
                    });
                    if (
                        this.productList[0].unitType != 0 &&
                        this.productList.length == 1
                    ) {
                        _this.$message({
                            message: "已启用多单位，商品规格不足",
                            type: "error",
                        });
                        _this.clicked = false;
                        return;
                    }
                    for (let i = 0; i < _this.productList.length; i++) {
                        delete this.productList[i].length;
                        if (this.productList[i].hasOwnProperty("isFirst")) {
                            delete this.productList[i].isFirst;
                        }
                        if (this.productList[i].hasOwnProperty("isChose")) {
                            delete this.productList[i].isChose;
                        }
                        if (this.productList[i].hasOwnProperty("isCount")) {
                            delete this.productList[i].isCount;
                        }
                        if (this.productList[i].hasOwnProperty("isClick")) {
                            delete this.productList[i].isClick;
                        }
                        _this.productList[i].name = _this.form.name;
                        _this.productList[i].productCategoryId =
                            _this.form.productCategoryId;
                        _this.productList[i].shortName = _this.form.shortName;
                        _this.productList[i].orders = _this.form.orders;
                        _this.productList[i].type = 1;
                        _this.productList[i].subType =2

                        _this.productList[i].publishType = _this.form.publishType;
                        _this.productList[i].isMarketable = false;
                        _this.productList[i].freightId = _this.form.freightId;
                        _this.productList[i].subTitle = _this.form.subTitle;
                        _this.productList[i].minLimit = _this.form.minLimit;
                        _this.productList[i].maxLimit = _this.form.maxLimit;
                        _this.productList[i].quality = _this.form.quality;
                        _this.productList[i].distributionId =
                            _this.form.distributionId;
                        _this.productList[i].brandId = _this.form.brandId;
                        // _this.productList[i].stock = _this.form.stock;
                        _this.productList[i].supplierId = _this.form.supplierId;
                        _this.productList[i].allocatedStock =
                            _this.form.allocatedStock;
                        _this.productList[i].weight = _this.form.weight;
                        _this.productList[i].goodsId = _this.form.goodsId;
                        _this.productList[i].article = _this.article;
                        _this.productList[
                            i
                        ].shippingMethod = _this.form.shippingMethod.toString();
                        if (
                            parseInt(_this.productList[i].minLimit) != 0 &&
                            parseInt(_this.productList[i].maxLimit) != 0 &&
                            parseInt(_this.productList[i].minLimit) >
                                parseInt(_this.productList[i].maxLimit)
                        ) {
                            _this.$message({
                                message: "最小订购量不可大于每日限量",
                                type: "success",
                            });
                            _this.clicked = false;
                            return;
                        }
                        if (_this.productList[i].sn == "") {
                            _this.$message({
                                message: "请完善货号/条码",
                                type: "error",
                            });
                            _this.clicked = false;
                            return;
                        }
                        if (utils.isNull(_this.productList[i].unit)) {
                            _this.productList[i].unit = "件";
                        }
                        if (utils.isNull(_this.productList[i].unitRate)) {
                            _this.productList[i].unitRate = 1;
                        }
                        if (utils.isNull(_this.productList[i].thumbnail)) {
                            _this.productList[i].thumbnail =
                                "http://cdn.rzico.com/weex/resources/images/defaultProduct.png";
                        }
                        if (utils.isNull(_this.productList[i].weight)) {
                            _this.productList[i].weight = 0;
                        }
                        if (utils.isNull(_this.productList[i].allocatedStock)) {
                            _this.productList[i].allocatedStock = 0;
                        }
                        if (utils.isNull(_this.productList[i].stock)) {
                            _this.productList[i].stock = 0;
                        }
                        if (utils.isNull(_this.productList[i].quality)) {
                            _this.productList[i].quality = 0;
                        }
                        if (
                            utils.isNull(_this.productList[i].minLimit) ||
                            _this.productList[i].minLimit < 1
                        ) {
                            _this.productList[i].minLimit = 1;
                        }
                        if (utils.isNull(_this.productList[i].marketPrice)) {
                            _this.productList[i].marketPrice = 0;
                        }
                        if (utils.isNull(_this.productList[i].price)) {
                            _this.productList[i].price = 0;
                        }
                        if (utils.isNull(_this.productList[i].cost)) {
                            _this.productList[i].cost = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip1price)) {
                            _this.productList[i].vip1price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip2price)) {
                            _this.productList[i].vip2price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip3price)) {
                            _this.productList[i].vip3price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip4price)) {
                            _this.productList[i].vip4price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip5price)) {
                            _this.productList[i].vip5price = 0;
                        }
                        if (utils.isNull(_this.productList[i].point)) {
                            _this.productList[i].point = 0;
                        }
                    }
                    console.log(this.productList);
                    update(_this.productList, params)
                        .then((response) => {
                            console.log(response);
                            _this.clicked = false;
                            EventBus.$emit("product-edit", response.data[0]);
                            _this.$store
                                .dispatch("tagsView/delView", _this.$route)
                                .then(({ visitedViews }) => {
                                    _this.$router.push({
                                        path: "/waterTicket/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            _this.clicked = false;
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
    },
};
</script>
